package com.itita.ww2.puredb;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

@MappedJdbcTypes(value = JdbcType.TIMESTAMP)
public class TimeStamp2LongTypeHandler extends BaseTypeHandler<Long> {

	@Override
	public Long getNullableResult(ResultSet arg0, String arg1) throws SQLException {
		Timestamp ts = null;
		try {
			ts = arg0.getTimestamp(arg1);
		} catch (SQLException e) {

		}
		if (ts == null) {
			return 0L;
		}
		return ts.getTime();
	}

	@Override
	public Long getNullableResult(ResultSet arg0, int arg1) throws SQLException {
		Timestamp ts = null;
		try {
			ts = arg0.getTimestamp(arg1);
		} catch (SQLException e) {
		}
		if (ts == null) {
			return 0L;
		}
		return ts.getTime();
	}

	@Override
	public Long getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
		Timestamp ts = null;
		try {
			ts = arg0.getTimestamp(arg1);
		} catch (SQLException e) {
		}
		if (ts == null) {
			return 0L;
		}
		return ts.getTime();
	}

	@Override
	public void setNonNullParameter(PreparedStatement arg0, int arg1, Long arg2, JdbcType arg3) throws SQLException {
		if (arg2 <= 0) {
			arg0.setTimestamp(arg1, null);
		} else {
			arg0.setTimestamp(arg1, new Timestamp(arg2.longValue()));
		}
	}

}
